%%%-------------------------------------------------------------------
%%% @author mirahs(2892727493@qq.com)
%%% @doc
%%%     角色工具
%%% @end
%%%-------------------------------------------------------------------
-module(role_misc).

-export([
    load/2
    ,login/2
    ,login_push/2
    ,logout/2
    ,newday/2
]).

-export([
    loop_check/1
]).

-include("common.hrl").
-include("link.hrl").
-include("role.hrl").
-include("role_data.hrl").
-include("pb.hrl").
-include("event.hrl").


%%%===================================================================
%%% event functions
%%%===================================================================

%% 初始化一些数据
load(Role = #role{date_reset = DateReset
    ,login_info = LoginInfo = #login_info{login_time = LastLogin, logout_time = LastLogout}
    ,link = #link{ip = Ip}}, _EventData
) ->
    LoginInfo2 = LoginInfo#login_info{
        login_time = util_time:unixtime(), login_ip = Ip, logout_time = 0
        ,last_login = LastLogin, last_logout = LastLogout
    },
    DateReset2 = ?IF(DateReset =:= undefined, util_time:date(), DateReset),

    Role2 = Role#role{
        date_reset = DateReset2, login_info = LoginInfo2
        ,event = role_event:init()
        ,is_online = 1
    },
    {ok, Role2}.

login(Role, _EventData) ->
    Date    = util_time:date(),
    Role2   = check_new_day(Role, Date),
    {ok, Role2}.

login_push(Role, _EventData) ->
    util_role:pack_send(?p_system_time, {util_time:unixtime()}),
    role_api:push_login(Role),
    ok.

logout(Role = #role{online_time = OnlineTime, login_info = LoginInfo = #login_info{login_time = LoginTime}}, _EventData) ->
    Time = util_time:unixtime(),

    LoginInfo2 = LoginInfo#login_info{logout_time = Time},

    Role2 = Role#role{online_time = OnlineTime + Time - LoginTime, login_info = LoginInfo2, is_online = 0},

    {ok, Role2}.

newday(Role = #role{}, #event_data{params = _IsLogin}) ->
    Role2 = Role#role{day_online = 0},
    {ok, Role2}.


%%%===================================================================
%%% API functions
%%%===================================================================

loop_check(Role) ->
    Role2 = add_online_time(Role),
    Role2.


%%%===================================================================
%%% Internal functions
%%%===================================================================

check_new_day(Role = #role{date_reset = DateReset}, DateReset) ->
    Role;
check_new_day(Role, Date) ->
    Role2 = Role#role{date_reset = Date},
    role_event:fire(Role2, ?event_role_newday).

add_online_time(Role = #role{day_online = DayOnline}) ->
    DayOnline2 = DayOnline + ?role_time_loop_check,
    NewRole = Role#role{day_online = DayOnline2},
    ?IF(DayOnline2 =/= 0 andalso DayOnline2 rem 60 =:= 0, role_event:fire(NewRole, ?event_role_online_minute), NewRole).
